import React, { FC, useEffect, useState, } from 'react'
import { Form, Input, Button } from 'antd-mobile'
import { reg } from '../utils/validate'
import { useCountDown } from 'ahooks'
import { Ajax } from './../api/api';
import { ShowSuccess } from '../utils/message';

const FormCaptcha: FC<any> = ({
    name,
    phone
}) => {
    const time = 180;
    const [toggle, setToggle] = useState<boolean>(true)
    const [targetDate, setTargetDate] = useState<number>();
    const [countdown] = useCountDown({
        targetDate,
        onEnd: () => {
            setToggle(true)
        }
    });
    const [disabled, setDisabled] = useState<boolean>(false)
    const todoSendCaptcha = async () => {
        let res = await Ajax.checkPhone({
            phone: phone
        }) as any;
        if (res.code == 200) {
            let res2 = await Ajax.sendCaptcha({
                phone: phone
            }) as any;
            if (res2.data) {
                ShowSuccess('验证码发送成功')
                setToggle(false)
                setTargetDate(Date.now() + time * 1000)
            }
        }
    }

    useEffect(() => {
        setDisabled(reg.phone.test(phone))
    }, [phone])


    return (
        <Form.Item
            name={name}
            label='验证码'
            rules={[
                { required: true },
                { pattern: reg.code, message: '请输入4位数字验证码' }
            ]}
            extra={
                <div className='size10'>
                    {
                        toggle ?
                            <Button disabled={!disabled} size={'small'} color='warning' onClick={todoSendCaptcha}  >发送验证码</Button>
                            :
                            <span>剩余{Math.floor(countdown / 1000)}S</span>
                    }
                </div>
            }
        >
            <Input placeholder='请输入' clearable />
        </Form.Item>
    )
}

FormCaptcha.defaultProps = {
    name: 'captcha'
}

export default FormCaptcha